<?php
/**
    fb_like v0.1
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    This file is part of the fbpost package. 
    
    fbpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    fbpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with fbpost. If not, see <http://www.gnu.org/licenses/>. 
**/

require_once(dirname(__FILE__)."/inc/common.php");

$addon_name = "fb_like<a name='fb_like'></a>";
$addon_version = "0.1";
$addon_description = "Adds the new template tags &lt;FB_META&gt;, "
    . "&lt;FB_INIT&gt; and &lt;FB_LIKE_BUTTON&gt; to insert Facebook "
    . "<em>Like</em> buttons on the image pages. <br />"
    . "The XFBML Like button implementation is used, so users will "
    . "always be able to enter an (optional) comment. <br />";

// don't do anything if plugin is disabled
if (!isAddonEnabled("fb_like")) return;

if (isset($_POST['fblike_do']) and $_POST['fblike_do'] == 'config') {
    // store updated configuration
    $app_id = trim($_POST['app_id']);
    $admin_id = trim($_POST['admin_id']);
    $layout = $_POST['layout'];
    $show_faces = isset($_POST['show_faces']) ? 1 : 0;
    $width = trim($_POST['width']);
    $action = $_POST['action'];
    $font = $_POST['font'];
    $colorscheme = $_POST['colorscheme'];
    $locale = $_POST['locale'];
    mysql_query("UPDATE " . TABLE_FBPOST_LIKE_CFG . " SET 
                 app_id='{$app_id}', 
                 admin_id='{$admin_id}', 
                 layout='{$layout}', 
                 show_faces='{$show_faces}', 
                 width={$width}, 
                 action='{$action}', 
                 font='{$font}', 
                 colorscheme='{$colorscheme}', 
                 locale='{$locale}'")
        or die(mysql_error());
    $_SESSION['fblike_result'] = 'Configuration saved. ';
}

// addons page or template tag hit
if ((isset($image_id) and preg_match("<(FB_LIKE_BUTTON|FB_INIT|FB_META)>", $tpl)) or 
    (isset($_GET['view']) and $_GET['view']=='addons')) {
    
    $SITE_URL = $cfgrow['siteurl'];
    
    // create config DB if it does not exist yet
    $res = mysql_query("SELECT * FROM " . TABLE_FBPOST_LIKE_CFG . " LIMIT 1");
    if (!$res) {
        mysql_query("CREATE TABLE IF NOT EXISTS " . TABLE_FBPOST_LIKE_CFG . " (
                     `app_id` VARCHAR(100), 
                     `admin_id` VARCHAR(100), 
                     `layout` VARCHAR(100), 
                     `show_faces` BOOL, 
                     `width` INT, 
                     `action` VARCHAR(100), 
                     `font` VARCHAR(100), 
                     `colorscheme` VARCHAR(100), 
                     `locale` CHAR(5)
                    )");
    }
    if (!$res or !mysql_num_rows($res) or mysql_num_rows($res) < 1) {
        // insert default config record
    	mysql_query("INSERT INTO " . TABLE_FBPOST_LIKE_CFG . " VALUES('', "
            . "'', 'standard', 1, 450, 'like', 'verdana', 'light', 'en_US')");
    }
    
    // populate config variables from config DB
    $result = mysql_query("SELECT * FROM " . TABLE_FBPOST_LIKE_CFG . " LIMIT 1");
    $cfg = mysql_fetch_array($result);
    
    // build configuration form (shown on admnin/addons page)
    $show_faces_checked = $cfg['show_faces'] ? "checked='checked'" : '';
    $addon_description .= <<<EOT
    <p>
        <strong>Configuration</strong><br />
        Specifying either Application ID or Admin user ID is sufficient 
        (in other words, you do not <em>need</em> a FB app to have a like 
        button on your page). <br />
        Additional information about these parameters can be found on 
        <a href="http://developers.facebook.com/docs/reference/plugins/like">developers.facebook.com</a>. 
    </p>
    <form action='{$SITE_URL}admin/index.php?view=addons#fb_like' method='post' accept-charset='UTF-8'>
        <input type='hidden' name='fblike_do' value='config' />
        <table>
            <tr style='vertical-align:top;'>
                <td>
                    Application ID:
                </td>
                <td><input type='text' size='40' name='app_id' value='{$cfg['app_id']}' /></td>
                <td>
                    <span style="font-size:0.8em;">(As shown on your FB 
                    <a href="http://www.facebook.com/developers/apps.php">applications 
                    page</a>)</span>
                </td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Admin user ID: <br />
                </td>
                <td><input type='text' size='40' name='admin_id' value='{$cfg['admin_id']}' /></td>
                <td>
                    <span style="font-size:0.8em;">(Find this on your FB profile 
                    page, e.g. in the link associated with your profile picture)</span>
                </td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Button layout: 
                </td>
                <td>
                    <select name='layout'>
EOT;
    foreach (FBConst::$LIKE_LAYOUTS as $key) {
        $selected = ($cfg['layout'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$key}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
                <td></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Show faces: </td>
                <td><input type='checkbox' name='show_faces' {$show_faces_checked} /></td>
                <td></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>
                    Width (in px): 
                </td>
                <td><input type='text' size='40' name='width' value='{$cfg['width']}' /></td>
                <td>
                    <span style="font-size:0.8em;">(Note the 
                    <a href="http://developers.facebook.com/docs/reference/plugins/like">minimum 
                    width</a>, according to the chosen layout)</span>
                </td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Verb to display: </td>
                <td>
                    <select name='action'>
EOT;
    foreach (FBConst::$LIKE_ACTIONS as $key) {
        $selected = ($cfg['action'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$key}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
                <td></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Font: </td>
                <td>
                    <select name='font'>
EOT;
    foreach (FBConst::$LIKE_FONTS as $key) {
        $selected = ($cfg['font'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$key}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
                <td></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Color scheme: </td>
                <td>
                    <select name='colorscheme'>
EOT;
    foreach (FBConst::$LIKE_COLORSCHEMES as $key) {
        $selected = ($cfg['colorscheme'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$key}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
                <td></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Language: </td>
                <td>
                    <select name='locale'>
EOT;
    foreach (FBConst::$LOCALES as $key => $val) {
        $selected = ($cfg['locale'] == $key) ? "selected='selected'" : '';
        $addon_description .= "<option value='{$key}' {$selected}>{$val}</option>";
    }
    $addon_description .= <<<EOT
                    </select>
                </td>
                <td></td>
            </tr>
        </table>
        <input type='submit' value='Save' />
    </form>
EOT;
    if (isset($_SESSION['fblike_result'])) {
        $addon_description .= "<p><em>" . $_SESSION['fblike_result'] . '</em></p>';
        unset($_SESSION['fblike_result']);
    }
}


/******************************************************************************
 * 
 * template tag substitution
 * 
 *****************************************************************************/

if (isset($image_id) and preg_match("<FB_LIKE_BUTTON>", $tpl)) {
    $str = <<<EOT
        <!-- BEGIN FACEBOOK LIKE BUTTON -->
        <fb:like layout='{$cfg['layout']}' show_faces='{$cfg['show_faces']}' width='{$cfg['width']}' action='{$cfg['action']}' font='{$cfg['font']}' colorscheme='{$cfg['colorscheme']}' ref='{$image_id}' />
        <!-- END FACEBOOK LIKE BUTTON -->
EOT;
    $tpl = str_replace("<FB_LIKE_BUTTON>", $str, $tpl);
}

if (isset($image_id) and preg_match("<FB_INIT>", $tpl)) {
    $str = <<<EOT
        <!-- BEGIN FACEBOOK INITIALIZATION -->
        <div id="fb-root"></div>
        <script type="text/javascript">
          window.fbAsyncInit = function() {
            FB.init({appId: '{$cfg['app_id']}', status: true, cookie: true, xfbml: true});
          };
          (function() {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/{$cfg['locale']}/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
          }());
        </script>
        <!-- END FACEBOOK INITIALIZATION -->
EOT;
    $tpl = str_replace("<FB_INIT>", $str, $tpl);
}

if (isset($image_id) and preg_match("<FB_META>", $tpl)) {
    $thumb_url = $SITE_URL . ltrim($cfgrow['thumbnailpath'], "./") . "thumb_".$image_name;
    $url = $SITE_URL . "index.php?showimage=" . $image_id;
    $desc = htmlentities(trim($image_notes_clean), ENT_QUOTES, "UTF-8");
    $desc = str_replace("\r", " ", str_replace("\n", " ", str_replace("\r\n", " ", $desc)));
    $desc = substr($desc, 0, 1000);
    $sitename = htmlentities($cfgrow['sitetitle'], ENT_QUOTES, "UTF-8");
    $str = <<<EOT
        <!-- BEGIN FACEBOOK/OPENGRAPH METADATA -->
        <meta property="og:type" content="article" />
        <meta property="og:title" content="{$image_title}" />
        <meta property="og:image" content="{$thumb_url}" />
        <meta property="og:url" content="{$url}" />
        <meta property="og:description" content="{$desc}" />
        <meta property="og:site_name" content="{$sitename}" />
EOT;
    if ($cfg['admin_id'] != "")
        $str .= "<meta property=\"fb:admins\" content=\"{$cfg['admin_id']}\" />\n";
    if ($cfg['app_id'] != "")
        $str .= "<meta property=\"fb:app_id\" content=\"{$cfg['app_id']}\" />\n";
    $str .= "<!-- END FACEBOOK/OPENGRAPH METADATA -->\n";
    $tpl = str_replace("<FB_META>", $str, $tpl);
}
?>